<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{this.$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!--  导航区    -->
      <el-page-header @back="goBack" :content="this.$router.currentRoute.name.substring(this.$router.currentRoute.name.indexOf('/')+1)">
      </el-page-header>

      <!-- 系统通知列表卡片区 -->
      <el-form :inline="true" ref="form"  size="small" style="margin-top: 2vh">
        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">条件查询区</h4>
        </el-row>
        <el-form-item >
          <el-input
              style="width: 140px;"
              clearable
              v-model="queryMap.resourceName"
              placeholder="请输入客户名称"
          ></el-input>
        </el-form-item>
        <el-form-item >
          <el-input
              style="width: 150px;"
              clearable
              v-model="queryMap.linkman"
              placeholder="请输入联系人名称"
          ></el-input>
        </el-form-item>
        <el-form-item >
          <el-input
              style="width: 130px;"
              clearable
              v-model="queryMap.phone"
              placeholder="请输入电话"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              style="width: 140px;"
              v-model="queryMap.options"
              placeholder="请选择行业类别"
          >
<!--            <el-option label="全部" value=""></el-option>-->
            <el-option v-for="dept in IndustryVOs" :key="dept.industryId" :label="dept.options" :value="dept.industryId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-input
              style="width: 140px;"
              clearable
              v-model="queryMap.taskPackageName"
              placeholder="请输入任务名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              style="width: 140px;"
              v-model="queryMap.resourceTag"
              placeholder="请选择标签资源"
          >
<!--            <el-option label="全部" value=""></el-option>-->
            <el-option label="未标记" value="0"></el-option>
            <el-option label="无效" value="1"></el-option>
            <el-option label="待定" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间筛选:">
          <el-select
              clearable
              style="width: 120px;"
              v-model="queryMap.timeType"
              placeholder="请选择时间"
          >
            <el-option label="创建时间" value="0"></el-option>
            <el-option label="呼叫时间" value="1"></el-option>
            <el-option label="更新时间" value="2"></el-option>
          </el-select>
          <el-date-picker
              type="daterange"
              align="right"
              unlink-panels
              @change="handleDateChange"
              v-model="queryDate"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item >
          <el-button @click="reset" icon="el-icon-refresh">重置</el-button>
          <el-button type="primary" @click="searchResource()" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>

      <div style="margin-bottom: 10px;display: flex">
        <span class="hint" style="flex: 1;"></span>
        <el-button style="" icon="el-icon-s-unfold"
                   v-hasPermission="'taskpackage_resource:batch'"
                   @click="confirmResourcesId">批量分配</el-button>
        <el-button style="" icon="el-icon-delete"
                   v-hasPermission="'taskpackage_resource:del'"
                   @click="delResources">批量删除</el-button>
        <el-button style="" icon="el-icon-download"
                   v-hasPermission="'taskpackage_resource:export'"
                   @click="downExcel">批量导出</el-button>
      </div>
      <!-- 表格区域 -->
      <el-table ref="multipleTable" :data="sysNoticeList"  size="small"
                @selection-change="handleSelectionChange"
                border style="width: 100%;" height="420">
        <el-table-column type="selection" prop="resourceId" width="40"></el-table-column>
        <el-table-column prop="taskPackageName" label="任务名称" width="100"></el-table-column>
        <el-table-column prop="resourceName" label="客户名称" width="100"></el-table-column>
        <el-table-column prop="linkman" label="联系人姓名" width="200"></el-table-column>
        <el-table-column prop="phoneA" label="电话A" width="200" ></el-table-column>
        <el-table-column prop="phoneB" label="电话B" width="200"></el-table-column>
        <el-table-column prop="options" label="行业类型" width="200"></el-table-column>
        <el-table-column prop="resourceTag" label="资源标签" width="200">
          <template v-slot="scope">
            <span>{{showTag(scope.row)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="200"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="100"></el-table-column>
        <el-table-column label="操作"  fixed="right" width="80">
          <template v-slot="scope">
            <el-tooltip content="删除" placement="top" effect="light"
                        v-hasPermission="'taskpackage_resource:del'">
              <el-button  type="danger" icon="el-icon-delete"
                          @click="()=>{multipleSelection.push({resourceId:scope.row.resourceId}); delResources()}"
                          plain circle ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNo"
          :page-sizes="this.$globalVar.sizes"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
      <!-- 选择用户窗口 -->
      <ElectUsersBox title="资源分配" @confirmUserId="confirmResourcesId" :isShow="electUsersBoxShow" @updateElectUsersBoxShow="electUsersBoxShow=false"/>
    </el-card>
  </div>
</template>
<script>
import axios from "axios";
import ElectUsersBox from "@/components/electUsersBox.vue";
export default {
  components: {ElectUsersBox},
  data() {
    // 计算最近一周的起始和结束日期
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
    end.setTime(end.getTime() + 3600 * 1000 * 24 * 1); // 当前时间减去 7 天
    return {
      electUsersBoxShow:false,
      total: 0,
      multipleSelection: [],
      sysNoticeList: [],
      value2: '',//日期选择器
      //查询对象
      queryMap: {
        pageNum: 1,
        pageSize: 10,
        taskPackageId:"",
        resourceId:"",
        taskPackageName:"",
        resourceName:"",
        linkman:"",
        phoneA:"",
        phoneB:"",
        isCall:"",
        options:"",
        resourceTag:"",
        createTime:"",
        nickName: "",
        remark:"",
        phone: "",
        agentStatus: "",
        NumberVerifStatus:"",
        isMove:"",
        deptId:"",
        timeType:"0",
        startDate: start,
        endDate: end,
      },
      queryDate: [start,end],
      IndustryVOs:[],
      tableData: [],
      batchAllocationMap:{},
      updateForm: {},

      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    };
  },
  methods: {
    /**
     * 加载未分配任务资源列表
     */
    async getNotAssignedResources() {
      const { data: res } = await this.$http.get("/tasking/undistributed/getNotAssignedList", {
        params: this.queryMap
      });
      if(!res.success){
        return this.$message.error("获取未分配资源列表失败:"+res.data.errorMsg);
      }
      this.total = res.data.total;
      this.sysNoticeList = res.data.rows;
      this.loading = false;
    },
    /**
     * 加载行业类型列表
     */
    async getAllIndustryList() {
      this.loading = true;
      try {
        const { data: res } = await this.$http.get("/tasking/findIndustryVOList");
        let validData = [];
        if (Array.isArray(res)) {
          validData = res;
        } else if (typeof res === 'object' && res.success) {
          validData = res.data || [];
        }
        if (Array.isArray(validData)) {
          this.IndustryVOs = validData.map(item => ({
            industryId: item.industryId,
            options: item.options
          }));
        }
      } catch (error) {
        // 处理其他异常
        console.error('获取行业类型列表时遇到异常', error);
        this.$message.error('获取行业类型列表时遇到异常');
      }
    },
    /**
     * 当时间选择时，直接赋值
     * @change="handleDateChange" 将其添加到时间中
     */
    handleDateChange() {
      this.queryMap.startDate = this.formatDate(this.queryDate[0],false);
      this.queryMap.endDate = this.formatDate(this.queryDate[1],true);
    },
    /**
     * 搜索任务资源
     */
    async searchResource() {
      this.queryMap.pageNum = 1;
      await this.getNotAssignedResources();
    },
    // 定义一个格式化时间的函数
    formatDate(date,is) {
      //判断时间是否为空
      if (date!=null){
        //判断是否为结束时间
        if (is){
          date.setDate(date.getDate() + 1);
        }
        const year = date.getFullYear();
        //+1，是因为月份是从0开始
        const month = ('0' + (date.getMonth()+1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);
        // console.log('格式化前各部分值: 年:', year,'月:', month,'日:', day);
        const hours = ('0' + date.getHours()).slice(-2);
        const minutes = ('0' + date.getMinutes()).slice(-2);
        const seconds = ('0' + date.getSeconds()).slice(-2);
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        // console.log('最终返回结果:', result);
      }
      return null;
    },
    /**
     * 接收传过来的任务包id
     */
    async getTaskPackageId() {
      const receivedValue = this.$route.query.taskPackageId; // 修改此处，获取名为taskPackageId的路由参数
      console.log(receivedValue);
      if (receivedValue) {
        // 确保queryMap已初始化，比如在data中定义为一个空对象
        this.queryMap = {
          ...this.queryMap,
          taskPackageId: receivedValue
        };
        await this.getNotAssignedResources();
      }else {
        await this.getNotAssignedResources();
      }
    },
    /**
     * 批量分配
     */
    async confirmResourcesId(uIds){
      if (this.multipleSelection.length==0){
        this.$message('未选择资源');
        return;
      }
      console.log("-"+uIds)
      //获取选中的资源id
      const rIds = this.multipleSelection.map(row => row.resourceId);
      //展示弹窗
      this.electUsersBoxShow=true
      console.log("+"+uIds)
      const createBatchAllocationMap = (uIds, rIds) => ({
        userIds: uIds,
        resourceIds: rIds
      });
      // 在confirmResourcesId方法中使用
      this.batchAllocationMap = createBatchAllocationMap(uIds, rIds);
      // 当用户确认分配时，发送请求
      if (uIds.length>0){
        const { data: res } = await this.$http.post("/tasking/batchAllocationResource/"+0, this.batchAllocationMap);
        console.log(res);
        if (res.data === "success"  ) {
          this.$message.success("分配资源成功");
        } else if (res.data === "isNull" ) {
          this.$message.warning("已分配资源");
        }else {
          this.$message.error("分配资源失败:" + res);
        }
        // 重新加载数据
        await this.getNotAssignedResources();
      }
    },
    /**
     * 加载任务资源表格
     */
    downExcel() {
      if (this.multipleSelection.length==0){
        this.$message('未选择资源');
        return;
      }
      //获取选中的资源id
      const ids = this.multipleSelection.map(row => row.resourceId);
      const $this = this;
      const res = axios
          .request({
            url: "http://47.99.186.44:8990/tasking/batchExport/"+ids,
            method: "post",
            responseType: "blob",
            headers:{'Authorization':LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)},	//设置请求头
          })
          .then(res => {
            if (res.headers["content-type"] === "application/json") {
              return $this.$message.error(
                  "Subject does not have permission [task:export]"
              );
            }
            const data = res.data;
            let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
            const a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = "任务资源列表.xls";
            a.click();
            window.URL.revokeObjectURL(url);
          });
    },
    /**
     * 删除资源
     */
    async delResources(){
      if (this.multipleSelection.length===0){
        this.$message('未选择资源');
        return;
      }
      const flag = await this.$confirm(
          "是否确认删除选中资源?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
        // 清空id列表
        this.multipleSelection = [];
      });
      if (!flag) {
        return;
      }
      //获取选中的资源id
      const rIds = this.multipleSelection.map(row => row.resourceId);
      // 当用户确认分配时，发送请求
      if (rIds.length>0){
        const { data: res } = await this.$http.post("/tasking/delByTPResourceId", rIds);
        console.log(res);
        if (res.data === "success"  ) {
          this.$message.success("删除资源成功");
        } else if (res.data === "isNull" ) {
          this.$message.warning("资源id不能为空");
        }else {
          this.$message.error("删除资源失败:" + res);
        }
        // 重新加载数据
        await this.getNotAssignedResources();
        //清空选中的资源
        this.multipleSelection = [];
      }
    },
    /**
     * 重置
     */
    reset() {
      this.queryMap= {
        pageNum: 1,
        pageSize: 10,
        taskPackageName:"",
        resourceName:"",
        linkman:"",
        phoneA:"",
        phoneB:"",
        isCall:"",
        options:"",
        resourceTag:"",
        createTime:"",
        nickName: "",
        isExists:"",
        remark:"",
        phone: "",
        agentStatus: "",
        NumberVerifStatus:"",
        isMove:"",
        deptId:"",
        timeType:"",
        startDate: null,
        endDate: null,
      };
      this.queryDate = [];
    },
    /**
     * 全选功能
     *
     */
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("******************************", val);
    },
    /**
     * 显示是否呼叫
     */
    showCall(row, column) {
      let call='';
      if(row.isCall==0){
        call = '未呼叫';
      }else if(row.isCall==1) {
        call = '已呼叫';
      }else{
        call = '未呼叫';
      }
      return call;
    },
    /**
     * 显示资源标签
     */
    showTag(row, column) {
      let tag='';
      if(row.resourceTag==0){
        tag = '未标记';
      }else if(row.resourceTag==1) {
        tag = '无效';
      }else if(row.resourceTag==2) {
        tag = '待定';
      }else if(row.resourceTag==3) {
        tag = '有效';
      }else{
        tag = '未标记';
      }
      return tag;
    },
    showExists(row, column){
      let value='';
      if(row.isExists==0){
        value = '不存在';
      }else if(row.isExists==1) {
        value = '已存在';
      }else{
        value = '不存在';
      }
      return value;
    },
    /**
     *  改变页码
     */
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getNotAssignedResources();
    },
    /**
     * 翻页
     */
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getNotAssignedResources();
    },
    /**
     * 退一步
     */
    goBack() {
      console.log('go back');
      window.history.back();
    },

  },
  created() {
    this.getAllIndustryList();
    // this.getNotAssignedResources();
    this.getTaskPackageId();
    // this.getAgentList();
  }
};
</script>

<style scoped>
.hint {
  margin-left: 2vh;
  font-weight: 400;
  font-size: 12px;
  color: red;
}

.dataDict {
  border: none;
  background-color: #fff;
  position: absolute;
  padding: .6vh 0;
  font-size: 18px;
}

.popups {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: 0%;
  background-color: #00000042;
  z-index: 100;
}

.popups .el-main {
  background-color: #fff;
  margin: 15vh auto;
}

.popups .el-main .header {
  display: flex;
  justify-content: center;
  margin-bottom: 2vh;
}

.popups .el-main .header button {
  flex-shrink: 0; /* 防止收缩 */
  font-size: 3vh;
  height: 4.6vh;
  border: none;
}
</style>
